package com.tianhui.consignortwofei.mvp.ui.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.fgs.common.CommonFragment;
import com.fgs.common.CommonPresenter;
import com.fgs.common.CommonResponse;
import com.fgs.common.CommonView;
import com.fgs.common.manager.ActivityManager;
import com.fgs.common.progress.ExceptionHandle;
import com.fgs.common.progress.ObserverResponseListener;
import com.fgs.common.utils.CommonUtil;
import com.fgs.common.utils.LogUtil;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.base.BaseActivity;
import com.tianhui.consignortwofei.constant.KeyValue;
import com.tianhui.consignortwofei.constant.OrderType;
import com.tianhui.consignortwofei.manager.EventBusManage;
import com.tianhui.consignortwofei.mvp.model.OrderModel;
import com.tianhui.consignortwofei.mvp.model.enty.DisplayPictureInfo;
import com.tianhui.consignortwofei.mvp.model.enty.FreightCalculationInfo;
import com.tianhui.consignortwofei.mvp.model.enty.OrderInfo;
import com.tianhui.consignortwofei.mvp.model.enty.detailItem.DetailFreightInfo;
import com.tianhui.consignortwofei.mvp.model.enty.detailItem.DetailFreightTipInfo;
import com.tianhui.consignortwofei.mvp.model.enty.detailItem.DetailInfo;
import com.tianhui.consignortwofei.mvp.model.enty.detailItem.DetailItemInfo;
import com.tianhui.consignortwofei.mvp.model.enty.detailItem.DetailLineInfo;
import com.tianhui.consignortwofei.mvp.model.enty.detailItem.DetailPictureInfo;
import com.tianhui.consignortwofei.mvp.ui.adapter.DetailAdapter;
import com.tianhui.consignortwofei.pattern.freightCalculation.CalculationController;
import com.xuexiang.xutil.common.StringUtils;

import org.yczbj.ycrefreshviewlib.inter.OnItemChildClickListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * @author fgs
 * @date 2020/9/8
 * @description
 **/
public class FreightActivity extends BaseActivity {

    @BindView(R.id.activity_freight_recyclerView)
    RecyclerView mRecyclerView;
    private DetailAdapter mAdapter;
    private OrderInfo mOrderInfo;
    private OrderModel mOrderModel;
    private String mGrantsPrice;
    private String mOtherPrice;
    private String mServicePrice;//信息服务费
    private String mDriverPrice;//司机运费
    private String mTotalPrice;//应付运费总价格
    private String mTotalTaxPrice;//含税应付运费总价格
    private String mGrantsRemark;
    private String mDeductRemark;

    private String zcPrice;
    private String ccPrice;

    private String mYunFeiPrice;//运费价格

    @Override
    public int getLayoutId() {
        return R.layout.activity_freight;
    }

    @Override
    public CommonPresenter createPresenter() {
        return null;
    }

    @Override
    public CommonView createView() {
        return null;
    }

    @Override
    public String getToolbarTitle() {
        return "运费计算";
    }

    @Override
    public void init() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);

        mAdapter = new DetailAdapter(this);
        mRecyclerView.setAdapter(mAdapter);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null && !bundle.isEmpty()) {
            mOrderInfo = bundle.getParcelable(KeyValue.KEY_ORDER_INFO);
            if (mOrderInfo != null)
                mAdapter.addAll(getDetailList(mOrderInfo));
        }

        initListener();

    }

    private void initListener() {
        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(View view, int position) {
                switch (view.getId()) {
                    case R.id.item_detail_freight_tip_submitButton:
                        requestOrderFreightCalculation();
                        break;
                    case R.id.item_detail_freight_tip_cancelButton:
                        finish();
                        break;
                }
            }
        });
        mAdapter.setOnFreightInputItemListener(new DetailAdapter.OnFreightInputItemListener() {
            @Override
            public void onInput(String goodsPrice, String price, String grants, String otherPrice, String zhuangChePrice, String cangChuPrice) {
                mYunFeiPrice = price;
                mOrderInfo.tradprice=mYunFeiPrice;
                mGrantsPrice = grants;
                mOtherPrice = otherPrice;
                mServicePrice = CalculationController.getInstance().getServicePrice(mOrderInfo, grants + "", otherPrice + "") + "";
                mDriverPrice = CalculationController.getInstance().getDriverPrice(mOrderInfo, goodsPrice + "", price + "", grants + "", otherPrice + "",zhuangChePrice,cangChuPrice);


                zcPrice = CommonUtil.keepTwoDecimal(cangChuPrice);
                ccPrice = CommonUtil.keepTwoDecimal(zhuangChePrice);

                mTotalPrice = CalculationController.getInstance().getTotalPrice(mOrderInfo, goodsPrice + "", price + "", grants + "", otherPrice + "",zhuangChePrice,cangChuPrice,mServicePrice);
                mTotalTaxPrice = CalculationController.getInstance().getTotalTaxPrice(mOrderInfo, goodsPrice + "", mOrderInfo.tradtaxprice, grants + "", otherPrice + "",zhuangChePrice,cangChuPrice,mServicePrice);
//                mTotalTaxPrice = CalculationController.getInstance().getTotalTaxPrice(mOrderInfo, goodsPrice, price, grants, otherPrice);


                LogUtil.print(mTotalPrice);

                Object object = mAdapter.getAllData().get(mAdapter.getCount() - 1);
                if (object instanceof DetailFreightTipInfo) {
                    DetailFreightTipInfo freightTipInfo = (DetailFreightTipInfo) object;
                    freightTipInfo.servicePrice = CommonUtil.keepTwoDecimal(mServicePrice);
                    freightTipInfo.driverOtherPrice = TextUtils.isEmpty(mOrderInfo.driverotherpirce) ? "0" : mOrderInfo.driverotherpirce;
                    freightTipInfo.driverPrice = CommonUtil.keepTwoDecimal(mDriverPrice);
                    freightTipInfo.totalPrice = CommonUtil.keepTwoDecimal(mTotalPrice);
                    freightTipInfo.taxTotalPrice = CommonUtil.keepTwoDecimal(mTotalTaxPrice);


                    freightTipInfo.brokercommission = mOrderInfo.brokercost + "";
                    if (mRecyclerView.isComputingLayout()) {
                        mRecyclerView.post(new Runnable() {
                            @Override
                            public void run() {
                                mAdapter.notifyItemChanged(mAdapter.getCount() - 1);
                            }
                        });

                    } else {
                        mAdapter.notifyItemChanged(mAdapter.getCount() - 1);
                    }
                }
            }

            @Override
            public void onRemarkInput(String grantsRemark, String deductRemark) {
                mGrantsRemark = grantsRemark;
                mDeductRemark = deductRemark;
                LogUtil.print(mGrantsRemark);
                LogUtil.print(mDeductRemark);
            }




        });
    }

    private void requestOrderFreightCalculation() {
        mOrderModel = new OrderModel();

        FreightCalculationInfo freightInfo = new FreightCalculationInfo();
//        freightInfo.fcprice = mOrderInfo.tradprice;
        freightInfo.fcprice = mYunFeiPrice;

        freightInfo.billno = mOrderInfo.billno;
        freightInfo.dispatchno = mOrderInfo.dispatchno;
        freightInfo.settleweight = mOrderInfo.recelveweightconfirm;
        freightInfo.settleweighttype = "";
        freightInfo.freightprice = mTotalPrice;

        if (TextUtils.isEmpty(mGrantsPrice)) {
            freightInfo.grants = "0";
        }else {
            freightInfo.grants = mGrantsPrice + "";
        }
//        freightInfo.grants = mGrantsPrice + "";
        freightInfo.loseweight = CalculationController.getInstance().getLoseWeight(mOrderInfo);
        freightInfo.fcremarks = mGrantsRemark;
        freightInfo.fcdeductremarks = mDeductRemark;
        freightInfo.otherpirce = mOtherPrice + "";
        freightInfo.brokercommission = mOrderInfo.brokercost + "";
//        freightInfo.iserror = (mTotalPrice.equals("0") || mDriverPrice.equals("0")) ? "1" : "0";
        freightInfo.reasonableloss = CommonUtil.keepThreeDecimal(StringUtils.toFloat(CalculationController.getInstance().getReasonableWeight(mOrderInfo)) * 1000 + "");
        freightInfo.deductpirce = CalculationController.getInstance().getDeductPrice(mOrderInfo);
        freightInfo.customerno = mOrderInfo.customerno;
        freightInfo.driveruserid = mOrderInfo.driveruserid;
        freightInfo.handlingprice = CalculationController.getInstance().getServicePrice(mOrderInfo, mGrantsPrice, mOtherPrice);
        freightInfo.settleprice = mDriverPrice;
        freightInfo.driverotherpirce = CalculationController.getInstance().getDriverOtherPrice(mOrderInfo);

        freightInfo.zcfprice = zcPrice;
        freightInfo.ccfprice = ccPrice;

        if (StringUtils.toFloat(mGrantsPrice) > 1000) {
            showToast("补助金金额不能超过1000");
            return;
        }

        if (StringUtils.toDouble(mTotalPrice) == 0 || StringUtils.toDouble(mDriverPrice) == 0) {

//        if (mTotalPrice.equals("0") || mDriverPrice.equals("0")) {
            freightInfo.iserror = "1";
            freightInfo.fciserror = "1";
            if (TextUtils.isEmpty(freightInfo.fcdeductremarks)) {
                showToast("运费计算为0或者负数，备注不能为空！");
                return;
            }
        } else {
            freightInfo.iserror = "0";
            freightInfo.fciserror = "0";
        }

        if (!TextUtils.isEmpty(mOtherPrice)&&!"0".equals(mOtherPrice)){
            if (TextUtils.isEmpty(freightInfo.fcdeductremarks)) {
                showToast("扣除费用不为0时，备注不能为空！");
                return;
            }
        }

//        int  rolePosition = SharedPreferenceManager.getInstance().getRolePosition();
//        if (2== rolePosition){
//            //2 销售，3物流
//            freightInfo.fcstatus="0";
//        }else {
//            freightInfo.fcstatus="1";
//        }

        mOrderModel.freightModel(this, freightInfo, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    EventBusManage.refreshOrderList();
                    finish();
                    ActivityManager.getInstance().finishActivity(OrderDetailActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putInt(KeyValue.KEY_TYPE, OrderType.TYPE_FREIGHT);
                    bundle.putParcelable(KeyValue.KEY_ORDER_INFO, mOrderInfo);
                    openActivity(OrderDetailActivity.class, bundle);
                } else {
                    showToast(commonResponse.getMsg());
                }

            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });
    }

    @Override
    public CommonFragment createFragment() {
        return null;
    }

    private List getDetailList(OrderInfo orderInfo) {
        List list = new ArrayList();

        DetailInfo detailInfo;
        DetailItemInfo detailItemInfo;
        DetailFreightInfo detailFreightInfo;
        DetailFreightTipInfo detailFreightTipInfo;
        DetailPictureInfo detailPictureInfo;
        DisplayPictureInfo displayPictureInfo;
        DetailLineInfo lineInfo;

        detailInfo = new DetailInfo();
        detailInfo.title = "货源单号：" + orderInfo.billno;
        detailInfo.topLeftText = "调度单号：" + orderInfo.dispatchno;
        detailInfo.topRightText = "货物类型：" + orderInfo.goodstypetext;

        detailInfo.infoList = new ArrayList<>();

        detailItemInfo = new DetailItemInfo();
        detailItemInfo.title = "姓名：";
        detailItemInfo.content = orderInfo.drivername;
        detailInfo.infoList.add(detailItemInfo);

        detailItemInfo = new DetailItemInfo();
        detailItemInfo.title = "车牌号：";
        detailItemInfo.content = orderInfo.vehiclenum;
        detailInfo.infoList.add(detailItemInfo);

        detailItemInfo = new DetailItemInfo();
        detailItemInfo.title = "联系方式：";
        detailItemInfo.content = orderInfo.drivertel;
        detailInfo.infoList.add(detailItemInfo);

        list.add(detailInfo);


        detailInfo = new DetailInfo();

        detailInfo.spanCount = 2;
        detailInfo.infoList = new ArrayList<>();

        detailItemInfo = new DetailItemInfo();
        detailItemInfo.title = "装车重量：";
        detailItemInfo.content = orderInfo.tranweight + "吨";
        detailInfo.infoList.add(detailItemInfo);

        detailItemInfo = new DetailItemInfo();
        detailItemInfo.title = "收货重量：";
        detailItemInfo.content = orderInfo.recelveweight + "吨";
        detailInfo.infoList.add(detailItemInfo);

        detailItemInfo = new DetailItemInfo();
        detailItemInfo.title = "结算重量：";
//        detailItemInfo.content = orderInfo.settleweight + "吨";
        detailItemInfo.content = orderInfo.recelveweightconfirm + "吨";
        detailInfo.infoList.add(detailItemInfo);

        list.add(detailInfo);

        lineInfo = new DetailLineInfo();
        list.add(lineInfo);


        detailPictureInfo = new DetailPictureInfo();
        detailPictureInfo.title = "单据信息";
        detailPictureInfo.isShowTitleTip = true;
        detailPictureInfo.list = new ArrayList<>();

        displayPictureInfo = new DisplayPictureInfo();
        displayPictureInfo.title = "装车单据";
        displayPictureInfo.imageId = orderInfo.loadingimg;
        detailPictureInfo.list.add(displayPictureInfo);

        displayPictureInfo = new DisplayPictureInfo();
        displayPictureInfo.title = "交货单据";
        displayPictureInfo.imageId = orderInfo.recepitbill;
        detailPictureInfo.list.add(displayPictureInfo);
        list.add(detailPictureInfo);

        lineInfo = new DetailLineInfo();
        list.add(lineInfo);

        detailFreightInfo = new DetailFreightInfo();
        detailFreightInfo.goodsPrice = orderInfo.goodsunitprice;
        detailFreightInfo.tradprice = orderInfo.tradprice;
        mYunFeiPrice=orderInfo.tradprice;
        detailFreightInfo.grants = orderInfo.grants;
        detailFreightInfo.otherPrice = orderInfo.otherpirce;
        detailFreightInfo.orderInfo = mOrderInfo;
        list.add(detailFreightInfo);

        lineInfo = new DetailLineInfo();
        list.add(lineInfo);


        detailFreightTipInfo = new DetailFreightTipInfo();
        detailFreightTipInfo.orderInfo = orderInfo;
        detailFreightTipInfo.insurePrice = orderInfo.insureprice;
        list.add(detailFreightTipInfo);

        return list;
    }
}
